package ybl.wechat;

import org.json.JSONObject;
import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.io.IOException;

public class ConfigSingleton {
    private static WeChatConf instance;

    private ConfigSingleton() {
    }

    public static WeChatConf getInstance() {
        if (instance == null) {
            Yaml yaml = new Yaml();

            try (InputStream inputStream = ConfigSingleton.class.getClassLoader()
                    .getResourceAsStream("wechat.yml")) {
                instance = yaml.loadAs(inputStream, WeChatConf.class);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Failed to load configuration");
            }
        }
        return instance;
    }

    /**
     * 读取menu.json文件并转换为JSONObject
     * 
     * @return JSONObject 如果文件存在并成功读取，返回JSONObject；否则返回null。
     */
    public static JSONObject getMenuConfig() {
        InputStream inputStream = ConfigSingleton.class.getClassLoader().getResourceAsStream("menu.json");
        if (inputStream == null) {
            System.out.println("menu.json does not exist");
            return null;
        }
        try {
            String jsonTxt = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
            return new JSONObject(jsonTxt);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Failed to read menu.json");
            return null;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
